package org.xsm.pinyougou.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.xsm.pinyougou.entity.TbSeckillGoods;
import org.xsm.pinyougou.entity.TbSeckillOrder;
import org.xsm.pinyougou.mapper.TbSeckillGoodsMapper;
import org.xsm.pinyougou.mapper.TbSeckillOrderMapper;
import org.xsm.pinyougou.utils.IdWorker;
import org.xsm.pinyougou.utils.OrderRecord;

import java.util.Date;

@Component
public class Xc implements Runnable{

    @Autowired
    TbSeckillOrderMapper tbSeckillOrderMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IdWorker idWorker;

    @Autowired
    TbSeckillGoodsMapper tbSeckillGoodsMapper;

    /**
     * 1、获取下单信息、包括商品id和用户userid，生成订单信息，加到数据库
     * 2、更新商品缓存信息
     */
    @Override
    public void run() {

        // 从线程里去除还没有处理 的订单
        // 里面有商品id和用户userId
        OrderRecord surplus = (OrderRecord) redisTemplate.boundListOps(OrderRecord.class.getSimpleName()).rightPop();

        if (surplus != null){
            // 查询这个用户要下单的商品数据
            TbSeckillGoods goods = (TbSeckillGoods) redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).get(surplus.getId());

            // 生成订单
            TbSeckillOrder seckillOrder = new TbSeckillOrder();

            seckillOrder.setUserId(surplus.getUserId());
            // 商家
            seckillOrder.setSellerId(goods.getSellerId());
            // 秒杀商品ID
            seckillOrder.setSeckillId(idWorker.nextId());
            seckillOrder.setMoney(goods.getCostPrice());
            seckillOrder.setCreateTime(new Date());
            seckillOrder.setStatus("0");//0-未支付

            // 把这个用户的订单数据存入TbSeckillOrder表
            tbSeckillOrderMapper.addOne(seckillOrder);

            // 加锁，一次只允许一个线程执行
            // 更新商品缓存信息
            synchronized (Xc.class){

                // 重新查信息，以防已修改
                goods = (TbSeckillGoods) redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).get(surplus.getId());

                // 库存-1
                goods.setStockCount(goods.getStockCount()-1);

                // 更新数据库，和redis里的redis缓存
                if (goods.getStockCount() <= 0){
                    redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).delete(surplus.getId());
                }else {
                    redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).put(surplus.getId(), goods);
                }
            }



        }


    }
}
